package com.shengwei.truck.driver.view.ui.settings;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.TimeCount;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.databinding.ActivityModifyPwdBinding;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.mine.userinfo.LoginActivity;
import com.shengwei.truck.driver.vm.ModifyPwdViewModel;

import java.lang.ref.WeakReference;

/**
 * 修改密码，忘记密码公用的页面
 */
public class ModifyPwdActivity extends BaseActivity<ModifyPwdViewModel, ActivityModifyPwdBinding> implements View.OnClickListener {
    private int mFromPage;
    private String mMobileNum;
    private String mPwd;
    private String mPwdSure;
    private String mSmsCode;
    private TimeCount mSmsTimeCount;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        getLastIntent();
        initLiveDataObersve();
        mSmsTimeCount = new TimeCount(mDataBinding.btGetSmsCode,60*1000,1000);
        this.getLifecycle().addObserver(mSmsTimeCount);
    }

    /**
     * 初始化及配置UI控件
     */
    private void initView() {
        mDataBinding.btSure.setOnClickListener(this);
        mDataBinding.btGetSmsCode.setOnClickListener(this);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_modify_pwd;
    }

    /**
     * 获取上页传递过来的数据
     */
    public void getLastIntent()
    {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mFromPage = bundle.getInt("fromPage");
            mMobileNum = bundle.getString("mobileNum");
            mDataBinding.setMobileNum(mMobileNum);
            String title = this.getResources().getString(R.string.app_name);

            if(mFromPage == MyConstant.FORGET_PASSWORD) {
                 title = this.getResources().getString(R.string.forget_pwd_title);
            }
            else if(mFromPage == MyConstant.MODIFY_PASSWORD){
                 title = this.getResources().getString(R.string.modify_pwd);
            }
            setToolBar(true,true,title);
        }
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        mViewModel.getModifyPwdLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> stringResult) {
                stringResult.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Toast.makeText(ModifyPwdActivity.this, R.string.modify_pwd_ok, Toast.LENGTH_SHORT).show();
                        User user = User.getInstance(getApplicationContext());
                        user.setToken("");
                        Intent i = new Intent(ModifyPwdActivity.this, LoginActivity.class);
                        i.putExtra("username", mMobileNum);
                        startActivity(i);
                    }
                });
            }
        });

        mViewModel.getSmsLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> stringResult) {
                stringResult.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        if (mSmsTimeCount != null){
                            mSmsTimeCount.start();
                        }
                        Toast.makeText(ModifyPwdActivity.this, R.string.smscode_ok,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btSure) {
            mSmsCode = mDataBinding.edtSmsCode.getText().toString().trim();
            mMobileNum = mDataBinding.edtMobileNum.getText().toString();
            mPwd = mDataBinding.edtPwd.getText().toString();
            mPwdSure = mDataBinding.edtPwdSure.getText().toString();
            boolean isCorrect = checkInput();

            if(isCorrect) {
                if(mFromPage == MyConstant.FORGET_PASSWORD) {
                    mViewModel.resetPwd(mMobileNum,mPwd,mSmsCode,"FORGET_PASSWORD");
                }
                else{  //修改密码页面
                    mViewModel.resetPwd("",mPwd,mSmsCode,"CHANGE_PASSWORD");
                }
            }
        }
        else if(v.getId() == R.id.btGetSmsCode) {
            getSmsCode();
        }
    }

    /**
     * 检查用户输入的字段是否合法
     * @return boolean : true合法，false不合法
     */
    public boolean checkInput()
    {
        boolean isCorrect = true;
        WeakReference<Context> weakReferenceContext = new WeakReference<>(ModifyPwdActivity.this);
        //手机号
        isCorrect = CommonUtil.checkMobile(mMobileNum,weakReferenceContext,true);

        //密码
        if(isCorrect) {
            isCorrect = CommonUtil.checkPassword(mPwd,weakReferenceContext,0);    //检查密码
        }
        //确认密码
        if(isCorrect) {
            isCorrect = CommonUtil.checkPassword(mPwdSure,weakReferenceContext,3); //检查确认密码
        }

        if(isCorrect) {
            //对比两此密码是否一致
            if (!mPwd.equals(mPwdSure)) {
                Toast.makeText(this,R.string.password_sure_incorrect,Toast.LENGTH_SHORT).show();
                mDataBinding.edtPwdSure.setText("");
                mDataBinding.edtPwdSure.setFocusable(true);
                isCorrect = false;
            }
        }

        //短信码
        if(isCorrect) {
            if (TextUtils.isEmpty(mSmsCode)) {
                Toast.makeText(this,R.string.smscode_empty,Toast.LENGTH_SHORT).show();
                isCorrect = false;
            }
        }
        return isCorrect;
    }

    /**
     * 获取短信验证码
     */
    private void getSmsCode() {
        String mobile = mDataBinding.edtMobileNum.getText().toString();
        WeakReference<Context> weakReferenceContext = new WeakReference<>(ModifyPwdActivity.this);

        //手机号格式检查
        boolean isCorrect = CommonUtil.checkMobile(mobile,weakReferenceContext,true);
        if(isCorrect) {
            mViewModel.getSmsCode(mobile,"FORGET_PASSWORD");
        }
    }
}